home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 4 / Apprentice-Release4.iso / Source Code / C / Applications / Python 1.3 / source code / Modules / socketmodule.c < prev    next >
Encoding:
C/C++ Source or Header  |  1995-12-17  |  36.9 KB  |  1,506 lines  |  [TEXT/R*ch]

  1. /***********************************************************
  2. Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
  3. The Netherlands.
  4.  
  5.                         All Rights Reserved
  6.  
  7. Permission to use, copy, modify, and distribute this software and its 
  8. documentation for any purpose and without fee is hereby granted, 
  9. provided that the above copyright notice appear in all copies and that
  10. both that copyright notice and this permission notice appear in 
  11. supporting documentation, and that the names of Stichting Mathematisch
  12. Centrum or CWI not be used in advertising or publicity pertaining to
  13. distribution of the software without specific, written prior permission.
  14.  
  15. STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
  16. THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  17. FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
  18. FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  19. WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  20. ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  21. OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  22.  
  23. ******************************************************************/
  24.  
  25. /* Socket module */
  26.  
  27. /*
  28. This module provides an interface to Berkeley socket IPC.
  29.  
  30. Limitations:
  31.  
  32. - only AF_INET and AF_UNIX address families are supported
  33. - no read/write operations (use send/recv or makefile instead)
  34.  
  35. Module interface:
  36.  
  37. - socket.error: exception raised for socket specific errors
  38. - socket.gethostbyname(hostname) --> host IP address (string: 'dd.dd.dd.dd')
  39. - socket.gethostbyaddr(IP address) --> (hostname, [alias, ...], [IP addr, ...])
  40. - socket.gethostname() --> host name (string: 'spam' or 'spam.domain.com')
  41. - socket.getservbyname(servicename, protocolname) --> port number
  42. - socket.socket(family, type [, proto]) --> new socket object
  43. - socket.AF_INET, socket.SOCK_STREAM, etc.: constants from <socket.h>
  44. - an Internet socket address is a pair (hostname, port)
  45.   where hostname can be anything recognized by gethostbyname()
  46.   (including the dd.dd.dd.dd notation) and port is in host byte order
  47. - where a hostname is returned, the dd.dd.dd.dd notation is used
  48. - a UNIX domain socket address is a string specifying the pathname
  49.  
  50. Socket methods:
  51.  
  52. - s.accept() --> new socket object, sockaddr
  53. - s.bind(sockaddr) --> None
  54. - s.close() --> None
  55. - s.connect(sockaddr) --> None
  56. - s.fileno() --> file descriptor
  57. - s.getpeername() --> sockaddr
  58. - s.getsockname() --> sockaddr
  59. - s.getsockopt(level, optname[, buflen]) --> int or string
  60. - s.listen(backlog) --> None
  61. - s.makefile([mode[, bufsize]]) --> file object
  62. - s.recv(buflen [,flags]) --> string
  63. - s.recvfrom(buflen [,flags]) --> string, sockaddr
  64. - s.send(string [,flags]) --> nbytes
  65. - s.sendto(string, [flags,] sockaddr) --> nbytes
  66. - s.setblocking(0 | 1) --> None
  67. - s.setsockopt(level, optname, value) --> None
  68. - s.shutdown(how) --> None
  69. - repr(s) --> "<socket object, fd=%d, family=%d, type=%d, protocol=%d>"
  70.  
  71. */
  72.  
  73. #include "Python.h"
  74.  
  75. #include <sys/types.h>
  76. #include "mytime.h"
  77.  
  78. #include <signal.h>
  79. #ifndef NT
  80. #include <netdb.h>
  81. #include <sys/socket.h>
  82. #include <netinet/in.h>
  83. #include <fcntl.h>
  84. #else
  85. #include <winsock.h>
  86. #include <fcntl.h>
  87. #endif
  88. #ifdef HAVE_SYS_UN_H
  89. #include <sys/un.h>
  90. #else
  91. #undef AF_UNIX
  92. #endif
  93.  
  94. #ifndef O_NDELAY
  95. #define O_NDELAY O_NONBLOCK    /* For QNX only? */
  96. #endif
  97.  
  98.  
  99. /* Here we have some hacks to choose between K&R or ANSI style function
  100.    definitions.  For NT to build this as an extension module (ie, DLL)
  101.    it must be compiled by the C++ compiler, as it takes the address of
  102.    a static data item exported from the main Python DLL.
  103. */
  104. #ifdef NT
  105. /* seem to be a few differences in the API */
  106. #define close closesocket
  107. #define NO_DUP    /* Define for NT 3.1, Win3.1 and Win95, Undefine for NT3.5 */
  108. #define FORCE_ANSI_FUNC_DEFS
  109. #endif
  110.  
  111. #ifdef FORCE_ANSI_FUNC_DEFS
  112. #define BUILD_FUNC_DEF_1( fnname, arg1type, arg1name )    \
  113. fnname( arg1type arg1name )
  114.  
  115. #define BUILD_FUNC_DEF_2( fnname, arg1type, arg1name, arg2type, arg2name ) \
  116. fnname( arg1type arg1name, arg2type arg2name )
  117.  
  118. #define BUILD_FUNC_DEF_3( fnname, arg1type, arg1name, arg2type, arg2name , arg3type, arg3name )    \
  119. fnname( arg1type arg1name, arg2type arg2name, arg3type arg3name )
  120.  
  121. #define BUILD_FUNC_DEF_4( fnname, arg1type, arg1name, arg2type, arg2name , arg3type, arg3name, arg4type, arg4name )    \
  122. fnname( arg1type arg1name, arg2type arg2name, arg3type arg3name, arg4type arg4name )
  123.  
  124. #else /* !FORCE_ANSI_FN_DEFS */
  125. #define BUILD_FUNC_DEF_1( fnname, arg1type, arg1name )    \
  126. fnname( arg1name )    \
  127.     arg1type arg1name;
  128.  
  129. #define BUILD_FUNC_DEF_2( fnname, arg1type, arg1name, arg2type, arg2name ) \
  130. fnname( arg1name, arg2name )    \
  131.     arg1type arg1name;    \
  132.     arg2type arg2name;
  133.  
  134. #define BUILD_FUNC_DEF_3( fnname, arg1type, arg1name, arg2type, arg2name, arg3type, arg3name ) \
  135. fnname( arg1name, arg2name, arg3name )    \
  136.     arg1type arg1name;    \
  137.     arg2type arg2name;    \
  138.     arg3type arg3name;
  139.  
  140. #define BUILD_FUNC_DEF_4( fnname, arg1type, arg1name, arg2type, arg2name, arg3type, arg3name, arg4type, arg4name ) \
  141. fnname( arg1name, arg2name, arg3name, arg4name )    \
  142.     arg1type arg1name;    \
  143.     arg2type arg2name;    \
  144.     arg3type arg3name;    \
  145.     arg4type arg4name;
  146.  
  147. #endif /* !FORCE_ANSI_FN_DEFS */
  148.  
  149. /* Global variable holding the exception type for errors detected
  150.    by this module (but not argument type or memory errors, etc.). */
  151.  
  152. static PyObject *PySocket_Error;
  153.  
  154.  
  155. /* Convenience function to raise an error according to errno
  156.    and return a NULL pointer from a function. */
  157.  
  158. static PyObject *
  159. PySocket_Err()
  160. {
  161. #ifdef NT
  162.     if (WSAGetLastError()) {
  163.         PyObject *v;
  164.         v = Py_BuildValue("(is)", WSAGetLastError(), "winsock error");
  165.         if (v != NULL) {
  166.             PyErr_SetObject(PySocket_Error, v);
  167.             Py_DECREF(v);
  168.         }
  169.         return NULL;
  170.     }
  171.     else
  172. #endif
  173.     return PyErr_SetFromErrno(PySocket_Error);
  174. }
  175.  
  176.  
  177. /* The object holding a socket.  It holds some extra information,
  178.    like the address family, which is used to decode socket address
  179.    arguments properly. */
  180.  
  181. typedef struct {
  182.     PyObject_HEAD
  183.     int sock_fd;        /* Socket file descriptor */
  184.     int sock_family;    /* Address family, e.g., AF_INET */
  185.     int sock_type;        /* Socket type, e.g., SOCK_STREAM */
  186.     int sock_proto;        /* Protocol type, usually 0 */
  187.     union sock_addr {
  188.         struct sockaddr_in in;
  189. #ifdef AF_UNIX
  190.         struct sockaddr_un un;
  191. #endif
  192.     } sock_addr;
  193. } PySocketSockObject;
  194.  
  195.  
  196. /* A forward reference to the Socktype type object.
  197.    The Socktype variable contains pointers to various functions,
  198.    some of which call newsockobject(), which uses Socktype, so
  199.    there has to be a circular reference. */
  200.  
  201. staticforward PyTypeObject PySocketSock_Type;
  202.  
  203.  
  204. /* Create a new socket object.
  205.    This just creates the object and initializes it.
  206.    If the creation fails, return NULL and set an exception (implicit
  207.    in NEWOBJ()). */
  208.  
  209. static PySocketSockObject *
  210. BUILD_FUNC_DEF_4(PySocketSock_New,int,fd, int,family, int,type, int,proto)
  211. {
  212.     PySocketSockObject *s;
  213.     s = PyObject_NEW(PySocketSockObject, &PySocketSock_Type);
  214.     if (s != NULL) {
  215.         s->sock_fd = fd;
  216.         s->sock_family = family;
  217.         s->sock_type = type;
  218.         s->sock_proto = proto;
  219.     }
  220.     return s;
  221. }
  222.  
  223.  
  224. /* Convert a string specifying a host name or one of a few symbolic
  225.    names to a numeric IP address.  This usually calls gethostbyname()
  226.    to do the work; the names "" and "<broadcast>" are special.
  227.    Return the length (should always be 4 bytes), or negative if
  228.    an error occurred; then an exception is raised. */
  229.  
  230. static int
  231. BUILD_FUNC_DEF_2(setipaddr, char*,name, struct sockaddr_in *,addr_ret)
  232. {
  233.     struct hostent *hp;
  234.     int d1, d2, d3, d4;
  235.     char ch;
  236. #ifdef HAVE_GETHOSTBYNAME_R
  237.     struct hostent hp_allocated;
  238.     char buf[1001];
  239.     int buf_len = (sizeof buf) - 1;
  240.     int errnop;
  241. #endif /* HAVE_GETHOSTBYNAME_R */
  242.  
  243.     if (name[0] == '\0') {
  244.         addr_ret->sin_addr.s_addr = INADDR_ANY;
  245.         return 4;
  246.     }
  247.     if (name[0] == '<' && strcmp(name, "<broadcast>") == 0) {
  248.         addr_ret->sin_addr.s_addr = INADDR_BROADCAST;
  249.         return 4;
  250.     }
  251.     if (sscanf(name, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 &&
  252.         0 <= d1 && d1 <= 255 && 0 <= d2 && d2 <= 255 &&
  253.         0 <= d3 && d3 <= 255 && 0 <= d4 && d4 <= 255) {
  254.         addr_ret->sin_addr.s_addr = htonl(
  255.             ((long) d1 << 24) | ((long) d2 << 16) |
  256.             ((long) d3 << 8) | ((long) d4 << 0));
  257.         return 4;
  258.     }
  259. #ifdef HAVE_GETHOSTBYNAME_R
  260.     Py_BEGIN_ALLOW_THREADS
  261.     hp = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop);
  262.     Py_END_ALLOW_THREADS
  263. #else /* not HAVE_GETHOSTBYNAME_R */
  264.     hp = gethostbyname(name);
  265. #endif /* HAVE_GETHOSTBYNAME_R */
  266.  
  267.     if (hp == NULL) {
  268. #ifdef HAVE_HSTRERROR
  269.             /* Let's get real error message to return */
  270.             extern int h_errno;
  271.         PyErr_SetString(PySocket_Error, (char *)hstrerror(h_errno));
  272. #else
  273.         PyErr_SetString(PySocket_Error, "host not found");
  274. #endif
  275.         return -1;
  276.     }
  277.     memcpy((char *) &addr_ret->sin_addr, hp->h_addr, hp->h_length);
  278.     return hp->h_length;
  279. }
  280.  
  281.  
  282. /* Create a string object representing an IP address.
  283.    This is always a string of the form 'dd.dd.dd.dd' (with variable
  284.    size numbers). */
  285.  
  286. static PyObject *
  287. BUILD_FUNC_DEF_1(makeipaddr, struct sockaddr_in *,addr)
  288. {
  289.     long x = ntohl(addr->sin_addr.s_addr);
  290.     char buf[100];
  291.     sprintf(buf, "%d.%d.%d.%d",
  292.         (int) (x>>24) & 0xff, (int) (x>>16) & 0xff,
  293.         (int) (x>> 8) & 0xff, (int) (x>> 0) & 0xff);
  294.     return PyString_FromString(buf);
  295. }
  296.  
  297.  
  298. /* Create an object representing the given socket address,
  299.    suitable for passing it back to bind(), connect() etc.
  300.    The family field of the sockaddr structure is inspected
  301.    to determine what kind of address it really is. */
  302.  
  303. /*ARGSUSED*/
  304. static PyObject *
  305. BUILD_FUNC_DEF_2(makesockaddr,struct sockaddr *,addr, int,addrlen)
  306. {
  307.     if (addrlen == 0) {
  308.         /* No address -- may be recvfrom() from known socket */
  309.         Py_INCREF(Py_None);
  310.         return Py_None;
  311.     }
  312.  
  313.     switch (addr->sa_family) {
  314.  
  315.     case AF_INET:
  316.     {
  317.         struct sockaddr_in *a = (struct sockaddr_in *) addr;
  318.         PyObject *addr = makeipaddr(a);
  319.         PyObject *ret = Py_BuildValue("Oi", addr, ntohs(a->sin_port));
  320.         Py_XDECREF(addr);
  321.         return ret;
  322.     }
  323.  
  324. #ifdef AF_UNIX
  325.     case AF_UNIX:
  326.     {
  327.         struct sockaddr_un *a = (struct sockaddr_un *) addr;
  328.         return PyString_FromString(a->sun_path);
  329.     }
  330. #endif /* AF_UNIX */
  331.  
  332.     /* More cases here... */
  333.  
  334.     default:
  335.         PyErr_SetString(PySocket_Error, "return unknown socket address type");
  336.         return NULL;
  337.  
  338.     }
  339. }
  340.  
  341.  
  342. /* Parse a socket address argument according to the socket object's
  343.    address family.  Return 1 if the address was in the proper format,
  344.    0 of not.  The address is returned through addr_ret, its length
  345.    through len_ret. */
  346.  
  347. static int
  348. BUILD_FUNC_DEF_4(
  349. getsockaddrarg,PySocketSockObject *,s, PyObject *,args, struct sockaddr **,addr_ret, int *,len_ret)
  350. {
  351.     switch (s->sock_family) {
  352.  
  353. #ifdef AF_UNIX
  354.     case AF_UNIX:
  355.     {
  356.         struct sockaddr_un* addr;
  357.         char *path;
  358.         int len;
  359.         addr = (struct sockaddr_un* )&(s->sock_addr).un;
  360.         if (!PyArg_Parse(args, "s#", &path, &len))
  361.             return 0;
  362.         if (len > sizeof addr->sun_path) {
  363.             PyErr_SetString(PySocket_Error, "AF_UNIX path too long");
  364.             return 0;
  365.         }
  366.         addr->sun_family = AF_UNIX;
  367.         memcpy(addr->sun_path, path, len);
  368.         addr->sun_path[len] = 0;
  369.         *addr_ret = (struct sockaddr *) addr;
  370.         *len_ret = len + sizeof addr->sun_family;
  371.         return 1;
  372.     }
  373. #endif /* AF_UNIX */
  374.  
  375.     case AF_INET:
  376.     {
  377.         struct sockaddr_in* addr;
  378.         char *host;
  379.         int port;
  380.          addr=(struct sockaddr_in*)&(s->sock_addr).in;
  381.         if (!PyArg_Parse(args, "(si)", &host, &port))
  382.             return 0;
  383.         if (setipaddr(host, addr) < 0)
  384.             return 0;
  385.         addr->sin_family = AF_INET;
  386.         addr->sin_port = htons(port);
  387.         *addr_ret = (struct sockaddr *) addr;
  388.         *len_ret = sizeof *addr;
  389.         return 1;
  390.     }
  391.  
  392.     /* More cases here... */
  393.  
  394.     default:
  395.         PyErr_SetString(PySocket_Error, "getsockaddrarg: bad family");
  396.         return 0;
  397.  
  398.     }
  399. }
  400.  
  401.  
  402. /* Get the address length according to the socket object's address family. 
  403.    Return 1 if the family is known, 0 otherwise.  The length is returned
  404.    through len_ret. */
  405.  
  406. static int
  407. BUILD_FUNC_DEF_2(getsockaddrlen,PySocketSockObject *,s, int *,len_ret)
  408. {
  409.     switch (s->sock_family) {
  410.  
  411. #ifdef AF_UNIX
  412.     case AF_UNIX:
  413.     {
  414.         *len_ret = sizeof (struct sockaddr_un);
  415.         return 1;
  416.     }
  417. #endif /* AF_UNIX */
  418.  
  419.     case AF_INET:
  420.     {
  421.         *len_ret = sizeof (struct sockaddr_in);
  422.         return 1;
  423.     }
  424.  
  425.     /* More cases here... */
  426.  
  427.     default:
  428.         PyErr_SetString(PySocket_Error, "getsockaddrarg: bad family");
  429.         return 0;
  430.  
  431.     }
  432. }
  433.  
  434.  
  435. /* s.accept() method */
  436.  
  437. static PyObject *
  438. BUILD_FUNC_DEF_2(PySocketSock_accept,PySocketSockObject *,s, PyObject *,args)
  439. {
  440.     char addrbuf[256];
  441.     int addrlen, newfd;
  442.     PyObject *sock, *addr, *res;
  443.     if (!PyArg_NoArgs(args))
  444.         return NULL;
  445.     if (!getsockaddrlen(s, &addrlen))
  446.         return NULL;
  447.     Py_BEGIN_ALLOW_THREADS
  448.     newfd = accept(s->sock_fd, (struct sockaddr *) addrbuf, &addrlen);
  449.     Py_END_ALLOW_THREADS
  450.     if (newfd < 0)
  451.         return PySocket_Err();
  452.     /* Create the new object with unspecified family,
  453.        to avoid calls to bind() etc. on it. */
  454.     sock = (PyObject *) PySocketSock_New(newfd,
  455.                     s->sock_family,
  456.                     s->sock_type,
  457.                     s->sock_proto);
  458.     if (sock == NULL)
  459.         close(newfd);
  460.     addr = makesockaddr((struct sockaddr *) addrbuf, addrlen);
  461.     res = Py_BuildValue("OO", sock, addr);
  462.     Py_XDECREF(sock);
  463.     Py_XDECREF(addr);
  464.     return res;
  465. }
  466.  
  467.  
  468. #if 0
  469. /* s.allowbroadcast() method */
  470. /* XXX obsolete -- will disappear in next release */
  471.  
  472. static PyObject *
  473. BUILD_FUNC_DEF_2(PySocketSock_allowbroadcast,PySocketSockObject *,s, PyObject *,args)
  474. {
  475.     int flag;
  476.     int res;
  477.     if (!PyArg_Parse(args, "i", &flag))
  478.         return NULL;
  479.     res = setsockopt(s->sock_fd, SOL_SOCKET, SO_BROADCAST,
  480.              (ANY *)&flag, sizeof flag);
  481.     if (res < 0)
  482.         return PySocket_Err();
  483.     Py_INCREF(Py_None);
  484.     return Py_None;
  485. }
  486. #endif
  487.  
  488.  
  489. /* s.setblocking(1 | 0) method */
  490.  
  491. static PyObject *
  492. BUILD_FUNC_DEF_2(PySocketSock_setblocking,PySocketSockObject*,s,PyObject*,args)
  493. {
  494.     int block;
  495.     int delay_flag;
  496.     if (!PyArg_GetInt(args, &block))
  497.         return NULL;
  498.     Py_BEGIN_ALLOW_THREADS
  499. #ifndef NT
  500.     delay_flag = fcntl (s->sock_fd, F_GETFL, 0);
  501.     if (block)
  502.         delay_flag &= (~O_NDELAY);
  503.     else
  504.         delay_flag |= O_NDELAY;
  505.     fcntl (s->sock_fd, F_SETFL, delay_flag);
  506. #else
  507.     block = !block;
  508.     ioctlsocket(s->sock_fd, FIONBIO, (u_long*)&block);
  509. #endif
  510.     Py_END_ALLOW_THREADS
  511.  
  512.     Py_INCREF(Py_None);
  513.     return Py_None;
  514. }
  515.  
  516.  
  517. /* s.setsockopt() method.
  518.    With an integer third argument, sets an integer option.
  519.    With a string third argument, sets an option from a buffer;
  520.    use optional built-in module 'struct' to encode the string. */
  521.  
  522. static PyObject *
  523. BUILD_FUNC_DEF_2(PySocketSock_setsockopt,PySocketSockObject *,s, PyObject *,args)
  524. {
  525.     int level;
  526.     int optname;
  527.     int res;
  528.     char *buf;
  529.     int buflen;
  530.     int flag;
  531.  
  532.     if (PyArg_Parse(args, "(iii)", &level, &optname, &flag)) {
  533.         buf = (char *) &flag;
  534.         buflen = sizeof flag;
  535.     }
  536.     else {
  537.         PyErr_Clear();
  538.         if (!PyArg_Parse(args, "(iis#)", &level, &optname, &buf, &buflen))
  539.             return NULL;
  540.     }
  541.     res = setsockopt(s->sock_fd, level, optname, (ANY *)buf, buflen);
  542.     if (res < 0)
  543.         return PySocket_Err();
  544.     Py_INCREF(Py_None);
  545.     return Py_None;
  546. }
  547.  
  548.  
  549. /* s.getsockopt() method.
  550.    With two arguments, retrieves an integer option.
  551.    With a third integer argument, retrieves a string buffer of that size;
  552.    use optional built-in module 'struct' to decode the string. */
  553.  
  554. static PyObject *
  555. BUILD_FUNC_DEF_2(PySocketSock_getsockopt,PySocketSockObject *,s, PyObject *,args)
  556. {
  557.     int level;
  558.     int optname;
  559.     int res;
  560.     PyObject *buf;
  561.     int buflen;
  562.     int flag;
  563.  
  564.     if (PyArg_Parse(args, "(ii)", &level, &optname)) {
  565.         int flag = 0;
  566.         int flagsize = sizeof flag;
  567.         res = getsockopt(s->sock_fd, level, optname,
  568.                  (ANY *)&flag, &flagsize);
  569.         if (res < 0)
  570.             return PySocket_Err();
  571.         return PyInt_FromLong(flag);
  572.     }
  573.     PyErr_Clear();
  574.     if (!PyArg_Parse(args, "(iii)", &level, &optname, &buflen))
  575.         return NULL;
  576.     if (buflen <= 0 || buflen > 1024) {
  577.         PyErr_SetString(PySocket_Error, "getsockopt buflen out of range");
  578.         return NULL;
  579.     }
  580.     buf = PyString_FromStringAndSize((char *)NULL, buflen);
  581.     if (buf == NULL)
  582.         return NULL;
  583.     res = getsockopt(s->sock_fd, level, optname,
  584.              (ANY *)PyString_AsString(buf), &buflen);
  585.     if (res < 0) {
  586.         Py_DECREF(buf);
  587.         return PySocket_Err();
  588.     }
  589.     _PyString_Resize(&buf, buflen);
  590.     return buf;
  591. }
  592.  
  593.  
  594. /* s.bind(sockaddr) method */
  595.  
  596. static PyObject *
  597. BUILD_FUNC_DEF_2(PySocketSock_bind,PySocketSockObject *,s, PyObject *,args)
  598. {
  599.     struct sockaddr *addr;
  600.     int addrlen;
  601.     int res;
  602.     if (!getsockaddrarg(s, args, &addr, &addrlen))
  603.         return NULL;
  604.     Py_BEGIN_ALLOW_THREADS
  605.     res = bind(s->sock_fd, addr, addrlen);
  606.     Py_END_ALLOW_THREADS
  607.     if (res < 0)
  608.         return PySocket_Err();
  609.     Py_INCREF(Py_None);
  610.     return Py_None;
  611. }
  612.  
  613.  
  614. /* s.close() method.
  615.    Set the file descriptor to -1 so operations tried subsequently
  616.    will surely fail. */
  617.  
  618. static PyObject *
  619. BUILD_FUNC_DEF_2(PySocketSock_close,PySocketSockObject *,s, PyObject *,args)
  620. {
  621.     if (!PyArg_NoArgs(args))
  622.         return NULL;
  623.     Py_BEGIN_ALLOW_THREADS
  624.     (void) close(s->sock_fd);
  625.     Py_END_ALLOW_THREADS
  626.     s->sock_fd = -1;
  627.     Py_INCREF(Py_None);
  628.     return Py_None;
  629. }
  630.  
  631.  
  632. /* s.connect(sockaddr) method */
  633.  
  634. static PyObject *
  635. BUILD_FUNC_DEF_2(PySocketSock_connect,PySocketSockObject *,s, PyObject *,args)
  636. {
  637.     struct sockaddr *addr;
  638.     int addrlen;
  639.     int res;
  640.     if (!getsockaddrarg(s, args, &addr, &addrlen))
  641.         return NULL;
  642.     Py_BEGIN_ALLOW_THREADS
  643.     res = connect(s->sock_fd, addr, addrlen);
  644.     Py_END_ALLOW_THREADS
  645.     if (res < 0)
  646.         return PySocket_Err();
  647.     Py_INCREF(Py_None);
  648.     return Py_None;
  649. }
  650.  
  651.  
  652. /* s.fileno() method */
  653.  
  654. static PyObject *
  655. BUILD_FUNC_DEF_2(PySocketSock_fileno,PySocketSockObject *,s, PyObject *,args)
  656. {
  657.     if (!PyArg_NoArgs(args))
  658.         return NULL;
  659.     return PyInt_FromLong((long) s->sock_fd);
  660. }
  661.  
  662.  
  663. /* s.getsockname() method */
  664.  
  665. static PyObject *
  666. BUILD_FUNC_DEF_2(PySocketSock_getsockname,PySocketSockObject *,s, PyObject *,args)
  667. {
  668.     char addrbuf[256];
  669.     int addrlen, res;
  670.     if (!PyArg_NoArgs(args))
  671.         return NULL;
  672.     if (!getsockaddrlen(s, &addrlen))
  673.         return NULL;
  674.     Py_BEGIN_ALLOW_THREADS
  675.     res = getsockname(s->sock_fd, (struct sockaddr *) addrbuf, &addrlen);
  676.     Py_END_ALLOW_THREADS
  677.     if (res < 0)
  678.         return PySocket_Err();
  679.     return makesockaddr((struct sockaddr *) addrbuf, addrlen);
  680. }
  681.  
  682.  
  683. #ifdef HAVE_GETPEERNAME        /* Cray APP doesn't have this :-( */
  684. /* s.getpeername() method */
  685.  
  686. static PyObject *
  687. BUILD_FUNC_DEF_2(PySocketSock_getpeername,PySocketSockObject *,s, PyObject *,args)
  688. {
  689.     char addrbuf[256];
  690.     int addrlen, res;
  691.     if (!PyArg_NoArgs(args))
  692.         return NULL;
  693.     if (!getsockaddrlen(s, &addrlen))
  694.         return NULL;
  695.     Py_BEGIN_ALLOW_THREADS
  696.     res = getpeername(s->sock_fd, (struct sockaddr *) addrbuf, &addrlen);
  697.     Py_END_ALLOW_THREADS
  698.     if (res < 0)
  699.         return PySocket_Err();
  700.     return makesockaddr((struct sockaddr *) addrbuf, addrlen);
  701. }
  702. #endif /* HAVE_GETPEERNAME */
  703.  
  704.  
  705. /* s.listen(n) method */
  706.  
  707. static PyObject *
  708. BUILD_FUNC_DEF_2(PySocketSock_listen,PySocketSockObject *,s, PyObject *,args)
  709. {
  710.     int backlog;
  711.     int res;
  712.     if (!PyArg_GetInt(args, &backlog))
  713.         return NULL;
  714.     Py_BEGIN_ALLOW_THREADS
  715.     if (backlog < 1)
  716.         backlog = 1;
  717.     res = listen(s->sock_fd, backlog);
  718.     Py_END_ALLOW_THREADS
  719.     if (res < 0)
  720.         return PySocket_Err();
  721.     Py_INCREF(Py_None);
  722.     return Py_None;
  723. }
  724.  
  725. #ifndef NO_DUP
  726. /* s.makefile(mode) method.
  727.    Create a new open file object referring to a dupped version of
  728.    the socket's file descriptor.  (The dup() call is necessary so
  729.    that the open file and socket objects may be closed independent
  730.    of each other.)
  731.    The mode argument specifies 'r' or 'w' passed to fdopen(). */
  732.  
  733. static PyObject *
  734. BUILD_FUNC_DEF_2(PySocketSock_makefile,PySocketSockObject *,s, PyObject *,args)
  735. {
  736.     extern int fclose Py_PROTO((FILE *));
  737.     char *mode = "r";
  738.     int bufsize = -1;
  739.     int fd;
  740.     FILE *fp;
  741.     PyObject *f;
  742.  
  743.     if (!PyArg_ParseTuple(args, "|si", &mode, &bufsize))
  744.         return NULL;
  745. #ifdef NT
  746.    if ( ((fd =  _open_osfhandle( s->sock_fd, _O_BINARY )) < 0) ||
  747.         ((fd = dup(fd)) < 0) || ((fp = fdopen(fd, mode)) == NULL)) {
  748. #else
  749.     if ((fd = dup(s->sock_fd)) < 0 ||
  750.         (fp = fdopen(fd, mode)) == NULL) {
  751. #endif
  752.         if (fd >= 0)
  753.             close(fd);
  754.         return PySocket_Err();
  755.     }
  756.     f = PyFile_FromFile(fp, "<socket>", mode, fclose);
  757.     if (f != NULL)
  758.         PyFile_SetBufSize(f, bufsize);
  759.     return f;
  760. }
  761. #endif /* NO_DUP */
  762.  
  763. /* s.recv(nbytes [,flags]) method */
  764.  
  765. static PyObject *
  766. BUILD_FUNC_DEF_2(PySocketSock_recv,PySocketSockObject *,s, PyObject *,args)
  767. {
  768.     int len, n, flags;
  769.     PyObject *buf;
  770.     flags = 0;
  771.     if (!PyArg_Parse(args, "i", &len)) {
  772.         PyErr_Clear();
  773.         if (!PyArg_Parse(args, "(ii)", &len, &flags))
  774.             return NULL;
  775.     }
  776.     buf = PyString_FromStringAndSize((char *) 0, len);
  777.     if (buf == NULL)
  778.         return NULL;
  779.     Py_BEGIN_ALLOW_THREADS
  780.     n = recv(s->sock_fd, PyString_AsString(buf), len, flags);
  781.     Py_END_ALLOW_THREADS
  782.     if (n < 0) {
  783.         Py_DECREF(buf);
  784.         return PySocket_Err();
  785.     }
  786.     if (_PyString_Resize(&buf, n) < 0)
  787.         return NULL;
  788.     return buf;
  789. }
  790.  
  791.  
  792. /* s.recvfrom(nbytes [,flags]) method */
  793.  
  794. static PyObject *
  795. BUILD_FUNC_DEF_2(PySocketSock_recvfrom,PySocketSockObject *,s, PyObject *,args)
  796. {
  797.     char addrbuf[256];
  798.     PyObject *buf, *addr, *ret;
  799.     int addrlen, len, n, flags;
  800.     flags = 0;
  801.     if (!PyArg_Parse(args, "i", &len)) {
  802.         PyErr_Clear();
  803.         if (!PyArg_Parse(args, "(ii)", &len, &flags))
  804.             return NULL;
  805.     }
  806.     if (!getsockaddrlen(s, &addrlen))
  807.         return NULL;
  808.     buf = PyString_FromStringAndSize((char *) 0, len);
  809.     if (buf == NULL)
  810.         return NULL;
  811.     Py_BEGIN_ALLOW_THREADS
  812.     n = recvfrom(s->sock_fd, PyString_AsString(buf), len, flags,
  813. #ifndef NT
  814.              (ANY *)addrbuf, &addrlen);
  815. #else
  816.              (struct sockaddr *)addrbuf, &addrlen);
  817. #endif
  818.     Py_END_ALLOW_THREADS
  819.     if (n < 0) {
  820.         Py_DECREF(buf);
  821.         return PySocket_Err();
  822.     }
  823.     if (_PyString_Resize(&buf, n) < 0)
  824.         return NULL;
  825.     addr = makesockaddr((struct sockaddr *)addrbuf, addrlen);
  826.     ret = Py_BuildValue("OO", buf, addr);
  827.     Py_XDECREF(addr);
  828.     Py_XDECREF(buf);
  829.     return ret;
  830. }
  831.  
  832.  
  833. /* s.send(data [,flags]) method */
  834.  
  835. static PyObject *
  836. BUILD_FUNC_DEF_2(PySocketSock_send,PySocketSockObject *,s, PyObject *,args)
  837. {
  838.     char *buf;
  839.     int len, n, flags;
  840.     flags = 0;
  841.     if (!PyArg_Parse(args, "s#", &buf, &len)) {
  842.         PyErr_Clear();
  843.         if (!PyArg_Parse(args, "(s#i)", &buf, &len, &flags))
  844.             return NULL;
  845.     }
  846.     Py_BEGIN_ALLOW_THREADS
  847.     n = send(s->sock_fd, buf, len, flags);
  848.     Py_END_ALLOW_THREADS
  849.     if (n < 0)
  850.         return PySocket_Err();
  851.     return PyInt_FromLong((long)n);
  852. }
  853.  
  854.  
  855. /* s.sendto(data, [flags,] sockaddr) method */
  856.  
  857. static PyObject *
  858. BUILD_FUNC_DEF_2(PySocketSock_sendto,PySocketSockObject *,s, PyObject *,args)
  859. {
  860.     PyObject *addro;
  861.     char *buf;
  862.     struct sockaddr *addr;
  863.     int addrlen, len, n, flags;
  864.     flags = 0;
  865.     if (!PyArg_Parse(args, "(s#O)", &buf, &len, &addro)) {
  866.         PyErr_Clear();
  867.         if (!PyArg_Parse(args, "(s#iO)", &buf, &len, &flags, &addro))
  868.             return NULL;
  869.     }
  870.     if (!getsockaddrarg(s, addro, &addr, &addrlen))
  871.         return NULL;
  872.     Py_BEGIN_ALLOW_THREADS
  873.     n = sendto(s->sock_fd, buf, len, flags, addr, addrlen);
  874.     Py_END_ALLOW_THREADS
  875.     if (n < 0)
  876.         return PySocket_Err();
  877.     return PyInt_FromLong((long)n);
  878. }
  879.  
  880.  
  881. /* s.shutdown(how) method */
  882.  
  883. static PyObject *
  884. BUILD_FUNC_DEF_2(PySocketSock_shutdown,PySocketSockObject *,s, PyObject *,args)
  885. {
  886.     int how;
  887.     int res;
  888.     if (!PyArg_GetInt(args, &how))
  889.         return NULL;
  890.     Py_BEGIN_ALLOW_THREADS
  891.     res = shutdown(s->sock_fd, how);
  892.     Py_END_ALLOW_THREADS
  893.     if (res < 0)
  894.         return PySocket_Err();
  895.     Py_INCREF(Py_None);
  896.     return Py_None;
  897. }
  898.  
  899.  
  900. /* List of methods for socket objects */
  901.  
  902. static PyMethodDef PySocketSock_methods[] = {
  903.     {"accept",        (PyCFunction)PySocketSock_accept},
  904. #if 0
  905.     {"allowbroadcast",    (PyCFunction)PySocketSock_allowbroadcast},
  906. #endif
  907.     {"setblocking",        (PyCFunction)PySocketSock_setblocking},
  908.     {"setsockopt",        (PyCFunction)PySocketSock_setsockopt},
  909.     {"getsockopt",        (PyCFunction)PySocketSock_getsockopt},
  910.     {"bind",        (PyCFunction)PySocketSock_bind},
  911.     {"close",        (PyCFunction)PySocketSock_close},
  912.     {"connect",        (PyCFunction)PySocketSock_connect},
  913.     {"fileno",        (PyCFunction)PySocketSock_fileno},
  914.     {"getsockname",        (PyCFunction)PySocketSock_getsockname},
  915. #ifdef HAVE_GETPEERNAME
  916.     {"getpeername",        (PyCFunction)PySocketSock_getpeername},
  917. #endif
  918.     {"listen",        (PyCFunction)PySocketSock_listen},
  919. #ifndef NO_DUP
  920.     {"makefile",        (PyCFunction)PySocketSock_makefile, 1},
  921. #endif
  922.     {"recv",        (PyCFunction)PySocketSock_recv},
  923.     {"recvfrom",        (PyCFunction)PySocketSock_recvfrom},
  924.     {"send",        (PyCFunction)PySocketSock_send},
  925.     {"sendto",        (PyCFunction)PySocketSock_sendto},
  926.     {"shutdown",        (PyCFunction)PySocketSock_shutdown},
  927.     {NULL,            NULL}        /* sentinel */
  928. };
  929.  
  930.  
  931. /* Deallocate a socket object in response to the last Py_DECREF().
  932.    First close the file description. */
  933.  
  934. static void
  935. BUILD_FUNC_DEF_1(PySocketSock_dealloc,PySocketSockObject *,s)
  936. {
  937.     (void) close(s->sock_fd);
  938.     PyMem_DEL(s);
  939. }
  940.  
  941.  
  942. /* Return a socket object's named attribute. */
  943.  
  944. static PyObject *
  945. BUILD_FUNC_DEF_2(PySocketSock_getattr,PySocketSockObject *,s, char *,name)
  946. {
  947.     return Py_FindMethod(PySocketSock_methods, (PyObject *) s, name);
  948. }
  949.  
  950.  
  951. static PyObject *
  952. BUILD_FUNC_DEF_1(PySocketSock_repr,PySocketSockObject *,s)
  953. {
  954.     PyObject *addro;
  955.     struct sockaddr *addr;
  956.     char buf[512];
  957.     PyObject *t, *comma, *v;
  958.     int i, len;
  959.     sprintf(buf, 
  960.         "<socket object, fd=%d, family=%d, type=%d, protocol=%d>", 
  961.         s->sock_fd, s->sock_family, s->sock_type, s->sock_proto);
  962.     t = PyString_FromString(buf);
  963.     return t;
  964. }
  965.  
  966.  
  967. /* Type object for socket objects. */
  968.  
  969. static PyTypeObject PySocketSock_Type = {
  970.     PyObject_HEAD_INIT(&PyType_Type)
  971.     0,
  972.     "socket",
  973.     sizeof(PySocketSockObject),
  974.     0,
  975.     (destructor)PySocketSock_dealloc, /*tp_dealloc*/
  976.     0,        /*tp_print*/
  977.     (getattrfunc)PySocketSock_getattr, /*tp_getattr*/
  978.     0,        /*tp_setattr*/
  979.     0,        /*tp_compare*/
  980.     (reprfunc)PySocketSock_repr, /*tp_repr*/
  981.     0,        /*tp_as_number*/
  982.     0,        /*tp_as_sequence*/
  983.     0,        /*tp_as_mapping*/
  984. };
  985.  
  986.  
  987. /* Python interface to gethostname(). */
  988.  
  989. /*ARGSUSED*/
  990. static PyObject *
  991. BUILD_FUNC_DEF_2(PySocket_gethostname,PyObject *,self, PyObject *,args)
  992. {
  993.     char buf[1024];
  994.     int res;
  995.     if (!PyArg_NoArgs(args))
  996.         return NULL;
  997.     Py_BEGIN_ALLOW_THREADS
  998.     res = gethostname(buf, (int) sizeof buf - 1);
  999.     Py_END_ALLOW_THREADS
  1000.     if (res < 0)
  1001.         return PySocket_Err();
  1002.     buf[sizeof buf - 1] = '\0';
  1003.     return PyString_FromString(buf);
  1004. }
  1005.  
  1006.  
  1007. /* Python interface to gethostbyname(name). */
  1008.  
  1009. /*ARGSUSED*/
  1010. static PyObject *
  1011. BUILD_FUNC_DEF_2(PySocket_gethostbyname,PyObject *,self, PyObject *,args)
  1012. {
  1013.     char *name;
  1014.     struct sockaddr_in addrbuf;
  1015.     if (!PyArg_Parse(args, "s", &name))
  1016.         return NULL;
  1017.     if (setipaddr(name, &addrbuf) < 0)
  1018.         return NULL;
  1019.     return makeipaddr(&addrbuf);
  1020. }
  1021.  
  1022. /* Python interface to gethostbyaddr(IP). */
  1023.  
  1024. /*ARGSUSED*/
  1025. static PyObject *
  1026. BUILD_FUNC_DEF_2(PySocket_gethostbyaddr,PyObject *,self, PyObject *, args)
  1027. {
  1028.         struct sockaddr_in addr;
  1029.     char *ip_num;
  1030.     struct hostent *h;
  1031.     int d1,d2,d3,d4;
  1032.     char ch, **pch;
  1033.     PyObject *rtn_tuple = (PyObject *)NULL;
  1034.     PyObject *name_list = (PyObject *)NULL;
  1035.     PyObject *addr_list = (PyObject *)NULL;
  1036.     PyObject *tmp;
  1037.  
  1038.     if (!PyArg_Parse(args, "s", &ip_num))
  1039.         return NULL;
  1040.     if (setipaddr(ip_num, &addr) < 0)
  1041.         return NULL;
  1042.     h = gethostbyaddr((char *)&addr.sin_addr,
  1043.               sizeof(addr.sin_addr),
  1044.               AF_INET);
  1045.     if (h == NULL) {
  1046. #ifdef HAVE_HSTRERROR
  1047.             /* Let's get real error message to return */
  1048.             extern int h_errno;
  1049.         PyErr_SetString(PySocket_Error, (char *)hstrerror(h_errno));
  1050. #else
  1051.         PyErr_SetString(PySocket_Error, "host not found");
  1052. #endif
  1053.         return NULL;
  1054.     }
  1055.     if ((name_list = PyList_New(0)) == NULL)
  1056.         goto err;
  1057.     if ((addr_list = PyList_New(0)) == NULL)
  1058.         goto err;
  1059.     for (pch = h->h_aliases; *pch != NULL; pch++) {
  1060.         tmp = PyString_FromString(*pch);
  1061.         if (tmp == NULL)
  1062.             goto err;
  1063.         PyList_Append(name_list, tmp);
  1064.         Py_DECREF(tmp);
  1065.     }
  1066.     for (pch = h->h_addr_list; *pch != NULL; pch++) {
  1067.         memcpy((char *) &addr.sin_addr, *pch, h->h_length);
  1068.         tmp = makeipaddr(&addr);
  1069.         if (tmp == NULL)
  1070.             goto err;
  1071.         PyList_Append(addr_list, tmp);
  1072.         Py_DECREF(tmp);
  1073.     }
  1074.     rtn_tuple = Py_BuildValue("sOO", h->h_name, name_list, addr_list);
  1075.  err:
  1076.     Py_XDECREF(name_list);
  1077.     Py_XDECREF(addr_list);
  1078.     return rtn_tuple;
  1079. }
  1080.  
  1081.  
  1082. /* Python interface to getservbyname(name).
  1083.    This only returns the port number, since the other info is already
  1084.    known or not useful (like the list of aliases). */
  1085.  
  1086. /*ARGSUSED*/
  1087. static PyObject *
  1088. BUILD_FUNC_DEF_2(PySocket_getservbyname,PyObject *,self, PyObject *,args)
  1089. {
  1090.     char *name, *proto;
  1091.     struct servent *sp;
  1092.     if (!PyArg_Parse(args, "(ss)", &name, &proto))
  1093.         return NULL;
  1094.     Py_BEGIN_ALLOW_THREADS
  1095.     sp = getservbyname(name, proto);
  1096.     Py_END_ALLOW_THREADS
  1097.     if (sp == NULL) {
  1098.         PyErr_SetString(PySocket_Error, "service/proto not found");
  1099.         return NULL;
  1100.     }
  1101.     return PyInt_FromLong((long) ntohs(sp->s_port));
  1102. }
  1103.  
  1104.  
  1105. /* Python interface to socket(family, type, proto).
  1106.    The third (protocol) argument is optional.
  1107.    Return a new socket object. */
  1108.  
  1109. /*ARGSUSED*/
  1110. static PyObject *
  1111. BUILD_FUNC_DEF_2(PySocket_socket,PyObject *,self, PyObject *,args)
  1112. {
  1113.     PySocketSockObject *s;
  1114.     int fd, family, type, proto;
  1115.     proto = 0;
  1116.     if (!PyArg_Parse(args, "(ii)", &family, &type)) {
  1117.         PyErr_Clear();
  1118.         if (!PyArg_Parse(args, "(iii)", &family, &type, &proto))
  1119.             return NULL;
  1120.     }
  1121.     Py_BEGIN_ALLOW_THREADS
  1122.     fd = socket(family, type, proto);
  1123.     Py_END_ALLOW_THREADS
  1124.     if (fd < 0)
  1125.         return PySocket_Err();
  1126.     s = PySocketSock_New(fd, family, type, proto);
  1127.     /* If the object can't be created, don't forget to close the
  1128.        file descriptor again! */
  1129.     if (s == NULL)
  1130.         (void) close(fd);
  1131.     /* From now on, ignore SIGPIPE and let the error checking
  1132.        do the work. */
  1133. #ifdef SIGPIPE      
  1134.     (void) signal(SIGPIPE, SIG_IGN);
  1135. #endif   
  1136.     return (PyObject *) s;
  1137. }
  1138.  
  1139. #ifndef NO_DUP
  1140. /* Create a socket object from a numeric file description.
  1141.    Useful e.g. if stdin is a socket.
  1142.    Additional arguments as for socket(). */
  1143.  
  1144. /*ARGSUSED*/
  1145. static PyObject *
  1146. BUILD_FUNC_DEF_2(PySocket_fromfd,PyObject *,self, PyObject *,args)
  1147. {
  1148.     PySocketSockObject *s;
  1149.     int fd, family, type, proto;
  1150.     proto = 0;
  1151.     if (!PyArg_Parse(args, "(iii)", &fd, &family, &type)) {
  1152.         PyErr_Clear();
  1153.         if (!PyArg_Parse(args, "(iiii)", &fd, &family, &type, &proto))
  1154.             return NULL;
  1155.     }
  1156.     /* Dup the fd so it and the socket can be closed independently */
  1157.     fd = dup(fd);
  1158.     if (fd < 0)
  1159.         return PySocket_Err();
  1160.     s = PySocketSock_New(fd, family, type, proto);
  1161.     /* From now on, ignore SIGPIPE and let the error checking
  1162.        do the work. */
  1163. #ifdef SIGPIPE      
  1164.     (void) signal(SIGPIPE, SIG_IGN);
  1165. #endif   
  1166.     return (PyObject *) s;
  1167. }
  1168. #endif /* NO_DUP */
  1169.  
  1170. /* List of functions exported by this module. */
  1171.  
  1172. static PyMethodDef PySocket_methods[] = {
  1173.     {"gethostbyname",    PySocket_gethostbyname},
  1174.     {"gethostbyaddr",    PySocket_gethostbyaddr},
  1175.     {"gethostname",        PySocket_gethostname},
  1176.     {"getservbyname",    PySocket_getservbyname},
  1177.     {"socket",        PySocket_socket},
  1178. #ifndef NO_DUP
  1179.     {"fromfd",        PySocket_fromfd},
  1180. #endif
  1181.     {NULL,            NULL}         /* Sentinel */
  1182. };
  1183.  
  1184.  
  1185. /* Convenience routine to export an integer value.
  1186.    For simplicity, errors (which are unlikely anyway) are ignored. */
  1187.  
  1188. static void
  1189. BUILD_FUNC_DEF_3(insint,PyObject *,d, char *,name, int,value)
  1190. {
  1191.     PyObject *v = PyInt_FromLong((long) value);
  1192.     if (v == NULL) {
  1193.         /* Don't bother reporting this error */
  1194.         PyErr_Clear();
  1195.     }
  1196.     else {
  1197.         PyDict_SetItemString(d, name, v);
  1198.         Py_DECREF(v);
  1199.     }
  1200. }
  1201.  
  1202.  
  1203. /* Initialize this module.
  1204.    This is called when the first 'import socket' is done,
  1205.    via a table in config.c, if config.c is compiled with USE_SOCKET
  1206.    defined. */
  1207.  
  1208. void
  1209. initsocket()
  1210. {
  1211.     PyObject *m, *d;
  1212.     m = Py_InitModule("socket", PySocket_methods);
  1213.     d = PyModule_GetDict(m);
  1214.     PySocket_Error = PyString_FromString("socket.error");
  1215.     if (PySocket_Error == NULL || 
  1216.         PyDict_SetItemString(d, "error", PySocket_Error) != 0)
  1217.         Py_FatalError("can't define socket.error");
  1218.     insint(d, "AF_INET", AF_INET);
  1219. #ifdef AF_UNIX
  1220.     insint(d, "AF_UNIX", AF_UNIX);
  1221. #endif /* AF_UNIX */
  1222.     insint(d, "SOCK_STREAM", SOCK_STREAM);
  1223.     insint(d, "SOCK_DGRAM", SOCK_DGRAM);
  1224.     insint(d, "SOCK_RAW", SOCK_RAW);
  1225.     insint(d, "SOCK_SEQPACKET", SOCK_SEQPACKET);
  1226.     insint(d, "SOCK_RDM", SOCK_RDM);
  1227.  
  1228. #ifdef    SO_DEBUG
  1229.     insint(d, "SO_DEBUG", SO_DEBUG);
  1230. #endif
  1231. #ifdef    SO_ACCEPTCONN
  1232.     insint(d, "SO_ACCEPTCONN", SO_ACCEPTCONN);
  1233. #endif
  1234. #ifdef    SO_REUSEADDR
  1235.     insint(d, "SO_REUSEADDR", SO_REUSEADDR);
  1236. #endif
  1237. #ifdef    SO_KEEPALIVE
  1238.     insint(d, "SO_KEEPALIVE", SO_KEEPALIVE);
  1239. #endif
  1240. #ifdef    SO_DONTROUTE
  1241.     insint(d, "SO_DONTROUTE", SO_DONTROUTE);
  1242. #endif
  1243. #ifdef    SO_BROADCAST
  1244.     insint(d, "SO_BROADCAST", SO_BROADCAST);
  1245. #endif
  1246. #ifdef    SO_USELOOPBACK
  1247.     insint(d, "SO_USELOOPBACK", SO_USELOOPBACK);
  1248. #endif
  1249. #ifdef    SO_LINGER
  1250.     insint(d, "SO_LINGER", SO_LINGER);
  1251. #endif
  1252. #ifdef    SO_OOBINLINE
  1253.     insint(d, "SO_OOBINLINE", SO_OOBINLINE);
  1254. #endif
  1255. #ifdef    SO_REUSEPORT
  1256.     insint(d, "SO_REUSEPORT", SO_REUSEPORT);
  1257. #endif
  1258.  
  1259. #ifdef    SO_SNDBUF
  1260.     insint(d, "SO_SNDBUF", SO_SNDBUF);
  1261. #endif
  1262. #ifdef    SO_RCVBUF
  1263.     insint(d, "SO_RCVBUF", SO_RCVBUF);
  1264. #endif
  1265. #ifdef    SO_SNDLOWAT
  1266.     insint(d, "SO_SNDLOWAT", SO_SNDLOWAT);
  1267. #endif
  1268. #ifdef    SO_RCVLOWAT
  1269.     insint(d, "SO_RCVLOWAT", SO_RCVLOWAT);
  1270. #endif
  1271. #ifdef    SO_SNDTIMEO
  1272.     insint(d, "SO_SNDTIMEO", SO_SNDTIMEO);
  1273. #endif
  1274. #ifdef    SO_RCVTIMEO
  1275.     insint(d, "SO_RCVTIMEO", SO_RCVTIMEO);
  1276. #endif
  1277. #ifdef    SO_ERROR
  1278.     insint(d, "SO_ERROR", SO_ERROR);
  1279. #endif
  1280. #ifdef    SO_TYPE
  1281.     insint(d, "SO_TYPE", SO_TYPE);
  1282. #endif
  1283.  
  1284.     /* Maximum number of connections for "listen" */
  1285. #ifdef    SOMAXCONN
  1286.     insint(d, "SOMAXCONN", SOMAXCONN);
  1287. #else
  1288.     insint(d, "SOMAXCONN", 5);    /* Common value */
  1289. #endif
  1290.  
  1291.     /* Flags for send, recv */
  1292. #ifdef    MSG_OOB
  1293.     insint(d, "MSG_OOB", MSG_OOB);
  1294. #endif
  1295. #ifdef    MSG_PEEK
  1296.     insint(d, "MSG_PEEK", MSG_PEEK);
  1297. #endif
  1298. #ifdef    MSG_DONTROUTE
  1299.     insint(d, "MSG_DONTROUTE", MSG_DONTROUTE);
  1300. #endif
  1301. #ifdef    MSG_EOR
  1302.     insint(d, "MSG_EOR", MSG_EOR);
  1303. #endif
  1304. #ifdef    MSG_TRUNC
  1305.     insint(d, "MSG_TRUNC", MSG_TRUNC);
  1306. #endif
  1307. #ifdef    MSG_CTRUNC
  1308.     insint(d, "MSG_CTRUNC", MSG_CTRUNC);
  1309. #endif
  1310. #ifdef    MSG_WAITALL
  1311.     insint(d, "MSG_WAITALL", MSG_WAITALL);
  1312. #endif
  1313. #ifdef    MSG_BTAG
  1314.     insint(d, "MSG_BTAG", MSG_BTAG);
  1315. #endif
  1316. #ifdef    MSG_ETAG
  1317.     insint(d, "MSG_ETAG", MSG_ETAG);
  1318. #endif
  1319.  
  1320.     /* Protocol level and numbers, usable for [gs]etsockopt */
  1321. #ifdef    SOL_SOCKET
  1322.     insint(d, "SOL_SOCKET", SOL_SOCKET);
  1323. #endif
  1324. #ifdef    IPPROTO_IP
  1325.     insint(d, "IPPROTO_IP", IPPROTO_IP);
  1326. #endif
  1327. #ifdef    IPPROTO_ICMP
  1328.     insint(d, "IPPROTO_ICMP", IPPROTO_ICMP);
  1329. #endif
  1330. #ifdef    IPPROTO_IGMP
  1331.     insint(d, "IPPROTO_IGMP", IPPROTO_IGMP);
  1332. #endif
  1333. #ifdef    IPPROTO_GGP
  1334.     insint(d, "IPPROTO_GGP", IPPROTO_GGP);
  1335. #endif
  1336. #ifdef    IPPROTO_TCP
  1337.     insint(d, "IPPROTO_TCP", IPPROTO_TCP);
  1338. #endif
  1339. #ifdef    IPPROTO_EGP
  1340.     insint(d, "IPPROTO_EGP", IPPROTO_EGP);
  1341. #endif
  1342. #ifdef    IPPROTO_PUP
  1343.     insint(d, "IPPROTO_PUP", IPPROTO_PUP);
  1344. #endif
  1345. #ifdef    IPPROTO_UDP
  1346.     insint(d, "IPPROTO_UDP", IPPROTO_UDP);
  1347. #endif
  1348. #ifdef    IPPROTO_IDP
  1349.     insint(d, "IPPROTO_IDP", IPPROTO_IDP);
  1350. #endif
  1351. #ifdef    IPPROTO_HELLO
  1352.     insint(d, "IPPROTO_HELLO", IPPROTO_HELLO);
  1353. #endif
  1354. #ifdef    IPPROTO_ND
  1355.     insint(d, "IPPROTO_ND", IPPROTO_ND);
  1356. #endif
  1357. #ifdef    IPPROTO_TP
  1358.     insint(d, "IPPROTO_TP", IPPROTO_TP);
  1359. #endif
  1360. #ifdef    IPPROTO_XTP
  1361.     insint(d, "IPPROTO_XTP", IPPROTO_XTP);
  1362. #endif
  1363. #ifdef    IPPROTO_EON
  1364.     insint(d, "IPPROTO_EON", IPPROTO_EON);
  1365. #endif
  1366. #ifdef    IPPROTO_BIP
  1367.     insint(d, "IPPROTO_BIP", IPPROTO_BIP);
  1368. #endif
  1369. /**/
  1370. #ifdef    IPPROTO_RAW
  1371.     insint(d, "IPPROTO_RAW", IPPROTO_RAW);
  1372. #endif
  1373. #ifdef    IPPROTO_MAX
  1374.     insint(d, "IPPROTO_MAX", IPPROTO_MAX);
  1375. #endif
  1376.  
  1377.     /* Some port configuration */
  1378. #ifdef    IPPORT_RESERVED
  1379.     insint(d, "IPPORT_RESERVED", IPPORT_RESERVED);
  1380. #else
  1381.     insint(d, "IPPORT_RESERVED", 1024);
  1382. #endif
  1383. #ifdef    IPPORT_USERRESERVED
  1384.     insint(d, "IPPORT_USERRESERVED", IPPORT_USERRESERVED);
  1385. #else
  1386.     insint(d, "IPPORT_USERRESERVED", 5000);
  1387. #endif
  1388.  
  1389.     /* Some reserved IP v.4 addresses */
  1390. #ifdef    INADDR_ANY
  1391.     insint(d, "INADDR_ANY", INADDR_ANY);
  1392. #else
  1393.     insint(d, "INADDR_ANY", 0x00000000);
  1394. #endif
  1395. #ifdef    INADDR_BROADCAST
  1396.     insint(d, "INADDR_BROADCAST", INADDR_BROADCAST);
  1397. #else
  1398.     insint(d, "INADDR_BROADCAST", 0xffffffff);
  1399. #endif
  1400. #ifdef    INADDR_LOOPBACK
  1401.     insint(d, "INADDR_LOOPBACK", INADDR_LOOPBACK);
  1402. #else
  1403.     insint(d, "INADDR_LOOPBACK", 0x7F000001);
  1404. #endif
  1405. #ifdef    INADDR_UNSPEC_GROUP
  1406.     insint(d, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP);
  1407. #else
  1408.     insint(d, "INADDR_UNSPEC_GROUP", 0xe0000000);
  1409. #endif
  1410. #ifdef    INADDR_ALLHOSTS_GROUP
  1411.     insint(d, "INADDR_ALLHOSTS_GROUP", INADDR_ALLHOSTS_GROUP);
  1412. #else
  1413.     insint(d, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
  1414. #endif
  1415. #ifdef    INADDR_MAX_LOCAL_GROUP
  1416.     insint(d, "INADDR_MAX_LOCAL_GROUP", INADDR_MAX_LOCAL_GROUP);
  1417. #else
  1418.     insint(d, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
  1419. #endif
  1420. #ifdef    INADDR_NONE
  1421.     insint(d, "INADDR_NONE", INADDR_NONE);
  1422. #else
  1423.     insint(d, "INADDR_NONE", 0xffffffff);
  1424. #endif
  1425.  
  1426.     /* IP [gs]etsockopt options */
  1427. #ifdef    IP_OPTIONS
  1428.     insint(d, "IP_OPTIONS", IP_OPTIONS);
  1429. #endif
  1430. #ifdef    IP_HDRINCL
  1431.     insint(d, "IP_HDRINCL", IP_HDRINCL);
  1432. #endif
  1433. #ifdef    IP_TOS
  1434.     insint(d, "IP_TOS", IP_TOS);
  1435. #endif
  1436. #ifdef    IP_TTL
  1437.     insint(d, "IP_TTL", IP_TTL);
  1438. #endif
  1439. #ifdef    IP_RECVOPTS
  1440.     insint(d, "IP_RECVOPTS", IP_RECVOPTS);
  1441. #endif
  1442. #ifdef    IP_RECVRETOPTS
  1443.     insint(d, "IP_RECVRETOPTS", IP_RECVRETOPTS);
  1444. #endif
  1445. #ifdef    IP_RECVDSTADDR
  1446.     insint(d, "IP_RECVDSTADDR", IP_RECVDSTADDR);
  1447. #endif
  1448. #ifdef    IP_RETOPTS
  1449.     insint(d, "IP_RETOPTS", IP_RETOPTS);
  1450. #endif
  1451. #ifdef    IP_MULTICAST_IF
  1452.     insint(d, "IP_MULTICAST_IF", IP_MULTICAST_IF);
  1453. #endif
  1454. #ifdef    IP_MULTICAST_TTL
  1455.     insint(d, "IP_MULTICAST_TTL", IP_MULTICAST_TTL);
  1456. #endif
  1457. #ifdef    IP_MULTICAST_LOOP
  1458.     insint(d, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP);
  1459. #endif
  1460. #ifdef    IP_ADD_MEMBERSHIP
  1461.     insint(d, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP);
  1462. #endif
  1463. #ifdef    IP_DROP_MEMBERSHIP
  1464.     insint(d, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP);
  1465. #endif
  1466. }
  1467.  
  1468. #ifdef NT
  1469. BOOL    WINAPI    DllMain (HANDLE hInst, 
  1470.             ULONG ul_reason_for_call,
  1471.             LPVOID lpReserved)
  1472. {
  1473.     const int opt = SO_SYNCHRONOUS_NONALERT;
  1474.     switch (ul_reason_for_call)
  1475.     {
  1476.         case DLL_PROCESS_ATTACH: {
  1477.             WSADATA WSAData;
  1478.             BOOL ok = TRUE;
  1479.             char buf[100] = "Python can't initialize Windows Sockets Module!\n\r";
  1480.             if (WSAStartup(MAKEWORD(1,1), &WSAData)) {
  1481.                 wsprintf(buf+strlen(buf), "WSAStartup failed (%d)",WSAGetLastError());
  1482.                 ok = FALSE;
  1483.             }
  1484.             /*
  1485.             ** Setup sockets in non-overlapped mode by default
  1486.             */
  1487.             if (ok && setsockopt(INVALID_SOCKET,SOL_SOCKET,SO_OPENTYPE,(const char *)&opt,sizeof(opt)) != 0) {
  1488.                 wsprintf(buf+strlen(buf),"setsockopt failed (%d)",WSAGetLastError());
  1489.                 ok = FALSE;
  1490.             }
  1491.             if (!ok) {
  1492.                 MessageBox(NULL,buf,"WinSock Error",MB_OK|MB_SETFOREGROUND);
  1493.                 return FALSE;
  1494.             }
  1495.             break;
  1496.         }
  1497.  
  1498.         case DLL_PROCESS_DETACH:
  1499.             WSACleanup();
  1500.             break;
  1501.  
  1502.     }
  1503.     return TRUE;
  1504. }
  1505. #endif /* NT */
  1506.